package com.typingtutor.ui.tabs;

import com.typingtutor.dto.*;
import com.typingtutor.model.Document;
import com.typingtutor.model.FieldKeyInfo;
import com.typingtutor.model.FieldKeyMappingRelation;
import com.typingtutor.model.Folder;
import com.typingtutor.ui.TypingTutor;
import com.typingtutor.ui.compose.CollapsibleListPanel;
import com.typingtutor.ui.compose.ExcelImporter;
import com.typingtutor.util.ResourcesUtils;
import com.typingtutor.util.UUIDUtils;
import lombok.Data;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.List;


@Data
public class DocumentTab {
    private JPanel panel;
    private JTree folderTree;
    private DefaultTreeModel treeModel;
    private DefaultMutableTreeNode rootNode;
    private DefaultListModel<Document> documentListModel;
    private JPopupMenu folderPopupMenu;
    private JPopupMenu documentPopupMenu;
    private ImageIcon folderIcon;
    private ImageIcon documentIcon;
    private final TypingTutor mainFrame;
    private JMenuItem importExcelMenuItem;
    // 新增：右侧词典配置面板
    private JPanel configPanel;
    private DefaultMutableTreeNode currentSelectedNode;


    public DocumentTab(TypingTutor mainFrame) {
        this.mainFrame = mainFrame;
        // 这里需要替换为实际的图标词条路径
        folderIcon = new ImageIcon(ResourcesUtils.getResourceFile("/img/icon/Folder.png"));
        documentIcon = new ImageIcon(ResourcesUtils.getResourceFile("/img/icon/Document.png"));
        // 初始化界面组件
        initComponents();
        // 加载根词典
        loadRootFolder();
    }

    private void initComponents() {
        panel = new JPanel(new BorderLayout());

        // 创建词典树
        rootNode = new DefaultMutableTreeNode();
        treeModel = new DefaultTreeModel(rootNode);
        folderTree = new JTree(treeModel);
        folderTree.getSelectionModel().addTreeSelectionListener(e -> {
            DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) folderTree.getLastSelectedPathComponent();
            if (selectedNode != null && selectedNode.getUserObject() instanceof Folder) {
                Folder selectedFolder = (Folder) selectedNode.getUserObject();
                loadDocumentsByFolder(selectedFolder.getId());
            }
        });

        // 设置自定义渲染器以显示图标
        DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer() {
            @Override
            public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
                super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
                if (node.getUserObject() instanceof Folder) {
                    Image image = folderIcon.getImage();
                    setIcon(new ImageIcon(image.getScaledInstance(20, 20, Image.SCALE_SMOOTH)));
                } else if (node.getUserObject() instanceof Document) {
                    Image image = documentIcon.getImage();
                    setIcon(new ImageIcon(image.getScaledInstance(15, 15, Image.SCALE_SMOOTH)));
                }
                return this;
            }
        };
        folderTree.setCellRenderer(renderer);

        JScrollPane treeScrollPane = new JScrollPane(folderTree);

        // 创建词典列表
        documentListModel = new DefaultListModel<>();

        // 创建词典右键菜单
        folderPopupMenu = new JPopupMenu();
        JMenuItem createFolderMenuItem = new JMenuItem("创建词典");
        createFolderMenuItem.addActionListener(e -> createFolder());
        folderPopupMenu.add(createFolderMenuItem);

        JMenuItem createDocumentMenuItem = new JMenuItem("创建词条");
        createDocumentMenuItem.addActionListener(e -> createDocument());
        folderPopupMenu.add(createDocumentMenuItem);

        JMenuItem renameFolderMenuItem = new JMenuItem("重命名词典");
        renameFolderMenuItem.addActionListener(e -> renameSelectedFolder());
        folderPopupMenu.add(renameFolderMenuItem);

        JMenuItem deleteFolderMenuItem = new JMenuItem("删除词典");
        deleteFolderMenuItem.addActionListener(e -> deleteSelectedFolder());
        folderPopupMenu.add(deleteFolderMenuItem);

        importExcelMenuItem = new JMenuItem("导入Excel");
        importExcelMenuItem.addActionListener(e -> {
            DefaultMutableTreeNode selectedFolderNode = (DefaultMutableTreeNode) folderTree.getLastSelectedPathComponent();
            if (selectedFolderNode != null && selectedFolderNode.getUserObject() instanceof Folder) {
                Folder selectedFolder = (Folder) selectedFolderNode.getUserObject();
                JFileChooser fileChooser = new JFileChooser();
                int result = fileChooser.showOpenDialog(panel);
                if (result == JFileChooser.APPROVE_OPTION) {
                    File selectedFile = fileChooser.getSelectedFile();
                    ExcelImporter.getInstance().importExcel(selectedFile, selectedFolder.getId());
                    // 清空根节点下的所有子节点
                    rootNode.removeAllChildren();
                    loadRootFolder();
                }
            }
        });
        folderPopupMenu.add(importExcelMenuItem);

        // 创建词典右键菜单
        documentPopupMenu = new JPopupMenu();
        JMenuItem renameDocumentMenuItem = new JMenuItem("重命名词条");
        renameDocumentMenuItem.addActionListener(e -> renameSelectedDocument());
        documentPopupMenu.add(renameDocumentMenuItem);

        JMenuItem deleteDocumentMenuItem = new JMenuItem("删除词条");
        deleteDocumentMenuItem.addActionListener(e -> deleteSelectedDocument());
        documentPopupMenu.add(deleteDocumentMenuItem);

        // 为词典树添加鼠标事件监听器
        folderTree.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                checkPopupTrigger(e);
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                checkPopupTrigger(e);
            }

            private void checkPopupTrigger(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    int row = folderTree.getRowForLocation(e.getX(), e.getY());
                    if (row != -1) {
                        folderTree.setSelectionRow(row);
                        currentSelectedNode = (DefaultMutableTreeNode) folderTree.getLastSelectedPathComponent();
                        if (currentSelectedNode != null && currentSelectedNode.getUserObject() instanceof Folder) {
                            folderPopupMenu.show(e.getComponent(), e.getX(), e.getY());
                        } else if (currentSelectedNode != null && currentSelectedNode.getUserObject() instanceof Document) {
                            documentPopupMenu.show(e.getComponent(), e.getX(), e.getY());
                        }
                    } else {
                        // 如果点击的不是树节点，显示空白区域的菜单
                        showPopupMenuForBlankArea(e);
                    }
                }
            }
        });
        // 创建占位符面板
        JLabel placeholderLabel = new JLabel();
        placeholderLabel.setHorizontalAlignment(JLabel.CENTER);
        configPanel = new JPanel(new BorderLayout());
        configPanel.add(placeholderLabel, BorderLayout.CENTER);
        // 当节点选择变化时，如果选中了 Document，则更新右侧配置面板
        folderTree.addTreeSelectionListener(e -> {
            DefaultMutableTreeNode selectedNode =
                    (DefaultMutableTreeNode) folderTree.getLastSelectedPathComponent();
            if (selectedNode != null && selectedNode.getUserObject() instanceof Document) {
                Document doc = (Document) selectedNode.getUserObject();
                updateDocumentConfigPanel(doc);
                // 创建右侧词条基本信息配置面板
                JPanel newConfigPanel = createDocumentConfigPanel(doc);
                configPanel.removeAll();
                configPanel.add(newConfigPanel, BorderLayout.CENTER);
                configPanel.revalidate();
                configPanel.repaint();
            } else if (selectedNode != null && selectedNode.getUserObject() instanceof Folder) {
                Folder folder = (Folder) selectedNode.getUserObject();
                updateFolderConfigPanel(folder);
                // 创建右侧词典基本信息配置面板
                JPanel newConfigPanel = createFolderConfigPanel(folder);
                configPanel.removeAll();
                configPanel.add(newConfigPanel, BorderLayout.CENTER);
                configPanel.revalidate();
                configPanel.repaint();
            } else {
                // 如果未选中词典，显示占位符
                configPanel.removeAll();
                configPanel.add(placeholderLabel, BorderLayout.CENTER);
                configPanel.revalidate();
                configPanel.repaint();
            }
        });

        // 整体界面：使用 JSplitPane 横向分割
        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, treeScrollPane, configPanel);
        splitPane.setDividerLocation(300);

        panel.add(splitPane);
    }


    private void showPopupMenuForBlankArea(MouseEvent e) {
        // 右键点击空白区域，显示词典创建菜单
        JPopupMenu blankAreaMenu = new JPopupMenu();
        JMenuItem createFolderMenuItem = new JMenuItem("创建词典");
        createFolderMenuItem.addActionListener(e1 -> createFolder());
        blankAreaMenu.add(createFolderMenuItem);
        blankAreaMenu.show(e.getComponent(), e.getX(), e.getY());
    }

    /**
     * 当用户点击一个词典节点时，更新右侧配置面板
     */
    private void updateDocumentConfigPanel(Document doc) {
        // 更新顶部名称栏
        Component[] comps = configPanel.getComponents();
        for(Component comp: comps){
            if(comp instanceof JPanel){
                JPanel sub = (JPanel) comp;
                for(Component c : sub.getComponents()){
                    if(c instanceof JTextField && "nameField".equals(c.getName())){
                        ((JTextField)c).setText(doc.getName());
                    }
                }
            }
        }
        // 如有存储该词典已有的配置，可以加载到动态区域，否则可先清空：
        JPanel fieldsPanel = null;
        for(Component comp : configPanel.getComponents()){
            if(comp instanceof JScrollPane){
                JScrollPane sp = (JScrollPane) comp;
                if(sp.getViewport().getView() instanceof JPanel){
                    JPanel panel = (JPanel) sp.getViewport().getView();
                    if("fieldsPanel".equals(panel.getName())){
                        fieldsPanel = panel;
                        break;
                    }
                }
            }
        }
        if(fieldsPanel != null){
            fieldsPanel.removeAll();
            fieldsPanel.revalidate();
            fieldsPanel.repaint();
        }
    }

    private void updateFolderConfigPanel(Folder folder) {
        // 更新顶部名称栏
        Component[] comps = configPanel.getComponents();
        for(Component comp: comps){
            if(comp instanceof JPanel){
                JPanel sub = (JPanel) comp;
                for(Component c : sub.getComponents()){
                    if(c instanceof JTextField && "nameField".equals(c.getName())){
                        ((JTextField)c).setText(folder.getName());
                    }
                }
            }
        }
        // 如有存储该词典已有的配置，可以加载到动态区域，否则可先清空：
        JPanel fieldsPanel = null;
        for(Component comp : configPanel.getComponents()){
            if(comp instanceof JScrollPane){
                JScrollPane sp = (JScrollPane) comp;
                if(sp.getViewport().getView() instanceof JPanel){
                    JPanel panel = (JPanel) sp.getViewport().getView();
                    if("fieldsPanel".equals(panel.getName())){
                        fieldsPanel = panel;
                        break;
                    }
                }
            }
        }
        if(fieldsPanel != null){
            fieldsPanel.removeAll();
            fieldsPanel.revalidate();
            fieldsPanel.repaint();
        }
    }

    private JPanel createDocumentConfigPanel(Document document) {
        // 整体面板
        JPanel configPanel = new JPanel(new BorderLayout(5, 5));
        configPanel.setBorder(new TitledBorder("词条基本信息配置"));

        // 中部区域：放置动态输入项（这里主要用于放置 JTree 以显示配置项）
        // 创建 fieldsPanel 并使用 BoxLayout 垂直排列组件
        final JPanel fieldsPanel = new JPanel();
        fieldsPanel.setLayout(new BoxLayout(fieldsPanel, BoxLayout.Y_AXIS));

        JScrollPane scrollPane = new JScrollPane(fieldsPanel);
        configPanel.add(scrollPane, BorderLayout.NORTH);

        CollapsibleListPanel uiPagePanel = new CollapsibleListPanel("界面显示配置", document);
        fieldsPanel.add(uiPagePanel);

        // 底部区域
        JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        DocumentDAO.getInstance().findConfigurationById(document.getId())
                .forEach(item -> {
                    List<FieldKeyMappingRelation> relations = FieldKeyMappingRelationDAO.getInstance().findByFieldMappingId(item.getId());
                    relations.forEach(relation -> {
                        FieldMappingDAO.getInstance().findById(relation.getFieldMappingId())
                                .forEach(field -> {
                                    FieldKeyInfo info = FieldKeyInfoDAO.getInstance().findAllFieldById(relation.getFieldKeyId());
                                    uiPagePanel.loadInputField(info.getFieldKey(), field.getFieldValue()
                                            , relation.getFieldMappingId(), relation.getFieldKeyId());
                                });
                    });
                });
        configPanel.add(bottomPanel, BorderLayout.SOUTH);
        return configPanel;
    }

    private JPanel createFolderConfigPanel(Folder folder) {
        // 整体面板
        JPanel configPanel = new JPanel(new BorderLayout(0, 0)); // 将边距设置为 0
        configPanel.setBorder(new TitledBorder("词典基本信息配置"));

        // 中部区域：放置动态输入项（这里主要用于放置 JTree 以显示配置项）
        // 创建 fieldsPanel 并使用 BoxLayout 垂直排列组件
        final JPanel fieldsPanel = new JPanel();
        fieldsPanel.setLayout(new BoxLayout(fieldsPanel, BoxLayout.Y_AXIS));

        JScrollPane scrollPane = new JScrollPane(fieldsPanel);
        scrollPane.setBorder(BorderFactory.createEmptyBorder()); // 去除滚动面板的边框
        configPanel.add(scrollPane, BorderLayout.CENTER);

        CollapsibleListPanel randomPagePanel = new CollapsibleListPanel("随机规则配置", folder);
        fieldsPanel.add(randomPagePanel);

        // 底部区域
        JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        bottomPanel.setBorder(BorderFactory.createEmptyBorder()); // 去除底部面板的边框
        FolderDAO.getInstance().findConfigurationById(folder.getId()).forEach(item -> {
            randomPagePanel.loadRadioButtonField(item.getId(), item.isDefaultEnabled(), folder);
        });

        ImageIcon runIcon = new ImageIcon(ResourcesUtils.getResourceFile("/img/icon/run.png"));
        Image runImg = runIcon.getImage().getScaledInstance(20, 20, Image.SCALE_SMOOTH);
        ImageIcon runScaledIcon = new ImageIcon(runImg);
        JButton runButton = new JButton(runScaledIcon);
        runButton.addActionListener(e -> {
            DefaultMutableTreeNode selectedFolderNode = (DefaultMutableTreeNode) folderTree.getLastSelectedPathComponent();
            if (selectedFolderNode != null && selectedFolderNode.getUserObject() instanceof Folder) {
                TypingTutor.addTab("词典练习", new TypingPracticeTab(mainFrame, (Folder) selectedFolderNode.getUserObject()).getPanel());
            }
        });

        bottomPanel.add(runButton);
        configPanel.add(bottomPanel, BorderLayout.SOUTH);
        return configPanel;
    }

    private void loadRootFolder() {
        List<Folder> rootFolders = FolderDAO.getInstance().getFoldersByParentId(null);
        for (Folder folder : rootFolders) {
            DefaultMutableTreeNode folderNode = new DefaultMutableTreeNode(folder);
            rootNode.add(folderNode);
            loadSubFolders(folderNode, folder.getId());
        }
        treeModel.reload();
    }

    private void loadSubFolders(DefaultMutableTreeNode parentNode, String parentFolderId) {
        List<Folder> subFolders = FolderDAO.getInstance().getFoldersByParentId(parentFolderId);
        for (Folder folder : subFolders) {
            DefaultMutableTreeNode folderNode = new DefaultMutableTreeNode(folder);
            parentNode.add(folderNode);
            loadSubFolders(folderNode, folder.getId());
        }

        List<Document> documents = DocumentDAO.getInstance().getDocumentsByFolderId(parentFolderId);
        for (Document document : documents) {
            DefaultMutableTreeNode documentNode = new DefaultMutableTreeNode(document);
            parentNode.add(documentNode);
        }
    }

    private void loadDocumentsByFolder(String folderId) {
        documentListModel.clear();
        List<Document> documents = DocumentDAO.getInstance().getDocumentsByFolderId(folderId);
        for (Document document : documents) {
            documentListModel.addElement(document);
        }
    }

    private void createFolder() {
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) folderTree.getLastSelectedPathComponent();
        if (selectedNode == null) {
            selectedNode = rootNode;
        }
        String parentFolderId = null;
        if (selectedNode.getUserObject() instanceof Folder) {
            parentFolderId = ((Folder) selectedNode.getUserObject()).getId();
        }
        String folderName = JOptionPane.showInputDialog(panel, "请输入词典名称");
        if (folderName != null && !folderName.isEmpty()) {
            String folderId = FolderDAO.getInstance().createFolder(UUIDUtils.getUUID(), folderName, parentFolderId);
            if (folderId != null && !folderId.isEmpty()) {
                Folder newFolder = new Folder(folderId, folderName, parentFolderId);
                DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(newFolder);
                selectedNode.add(newNode);
                treeModel.reload(selectedNode);
            }
        }
    }

    private void createDocument() {
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) folderTree.getLastSelectedPathComponent();
        if (selectedNode != null && selectedNode.getUserObject() instanceof Folder) {
            Folder selectedFolder = (Folder) selectedNode.getUserObject();
            String documentName = JOptionPane.showInputDialog(panel, "请输入词条名称");
            if (documentName != null && !documentName.isEmpty()) {
                String documentId = DocumentDAO.getInstance().createDocument(UUIDUtils.getUUID(),documentName, selectedFolder.getId());
                if (documentId != null && !documentId.isEmpty()) {
                    Document newDocument = new Document(documentId, documentName, selectedFolder.getId());
                    DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(newDocument);
                    selectedNode.add(newNode);
                    treeModel.reload(selectedNode);
                    loadDocumentsByFolder(selectedFolder.getId());
                }
            }
        }
    }

    private void renameSelectedFolder() {
        DefaultMutableTreeNode selectedFolderNode = (DefaultMutableTreeNode) folderTree.getLastSelectedPathComponent();
        if (selectedFolderNode != null && selectedFolderNode.getUserObject() instanceof Folder) {
            Folder selectedFolder = (Folder) selectedFolderNode.getUserObject();
            String newName = JOptionPane.showInputDialog(panel, "请输入新的词典名称", selectedFolder.getName());
            if (newName != null && !newName.isEmpty()) {
                if (FolderDAO.getInstance().updateFolderName(selectedFolder.getId(), newName)) {
                    selectedFolder.setName(newName);
                    treeModel.reload(selectedFolderNode);
                }
            }
        }
    }

    private void renameSelectedDocument() {
        DefaultMutableTreeNode selectedDocumentNode = (DefaultMutableTreeNode) folderTree.getLastSelectedPathComponent();
        if (selectedDocumentNode != null && selectedDocumentNode.getUserObject() instanceof Document) {
            Document selectedDocument = (Document) selectedDocumentNode.getUserObject();
            String newName = JOptionPane.showInputDialog(panel, "请输入新的词典名称", selectedDocument.getName());
            if (newName != null && !newName.isEmpty()) {
                if (DocumentDAO.getInstance().updateDocument(selectedDocument.getId(), newName)) {
                    selectedDocument.setName(newName);
                    treeModel.reload(selectedDocumentNode);
                    loadDocumentsByFolder(selectedDocument.getFolderId());
                }
            }
        }
    }

    private void deleteSelectedFolder() {
        DefaultMutableTreeNode selectedFolderNode = (DefaultMutableTreeNode) folderTree.getLastSelectedPathComponent();
        if (selectedFolderNode != null && selectedFolderNode.getUserObject() instanceof Folder) {
            Folder selectedFolder = (Folder) selectedFolderNode.getUserObject();
            int confirm = JOptionPane.showConfirmDialog(panel, "确定要删除该词典及其所有子词典和词典吗？", "确认删除", JOptionPane.YES_NO_OPTION);
            if (confirm == JOptionPane.YES_OPTION) {
                // 递归删除子词典和词典
                deleteFolderAndChildren(selectedFolderNode);
                // 删除数据库中的词典记录
                if (FolderDAO.getInstance().deleteFolder(selectedFolder.getId())) {
                    treeModel.removeNodeFromParent(selectedFolderNode);
                    loadDocumentsByFolder(String.valueOf(-1));
                }
            }
        }
    }

    // 递归删除词典及其子词典和词典
    private void deleteFolderAndChildren(DefaultMutableTreeNode folderNode) {
        for (int i = folderNode.getChildCount() - 1; i >= 0; i--) {
            DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) folderNode.getChildAt(i);
            if (childNode.getUserObject() instanceof Folder) {
                // 递归删除子词典
                deleteFolderAndChildren(childNode);
                Folder childFolder = (Folder) childNode.getUserObject();
                // 删除数据库中的子词典记录
                FolderDAO.getInstance().deleteFolder(childFolder.getId());
                treeModel.removeNodeFromParent(childNode);
            } else if (childNode.getUserObject() instanceof Document) {
                Document childDocument = (Document) childNode.getUserObject();
                // 删除数据库中的词典记录
                DocumentDAO.getInstance().deleteDocument(childDocument.getId());
                treeModel.removeNodeFromParent(childNode);
            }
        }
    }

    private void deleteSelectedDocument() {
        DefaultMutableTreeNode selectedDocumentNode = (DefaultMutableTreeNode) folderTree.getLastSelectedPathComponent();
        if (selectedDocumentNode != null && selectedDocumentNode.getUserObject() instanceof Document) {
            Document selectedDocument = (Document) selectedDocumentNode.getUserObject();
            int confirm = JOptionPane.showConfirmDialog(panel, "确定要删除该词典吗？", "确认删除", JOptionPane.YES_NO_OPTION);
            if (confirm == JOptionPane.YES_OPTION) {
                if (DocumentDAO.getInstance().deleteDocument(selectedDocument.getId())) {
                    treeModel.removeNodeFromParent(selectedDocumentNode);
                    loadDocumentsByFolder(selectedDocument.getFolderId());
                }
            }
        }
    }
}